package com.fenghen.controller;

import com.fenghen.config.Result;
import com.fenghen.dto.LoginDTO;
import com.fenghen.entity.Redis;
import com.fenghen.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/redistest")
public class RedisController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplatez;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/test")
    public Result test() {
        List<Redis> list = redisService.list();
        return Result.ok(list);
    }

    @GetMapping("/save")
    public Result saveTest() {
        Redis redis = new Redis();
        redis.setUsername("wangba");
        // 使用 RedisTemplate 存储 Redis 对象
        redisTemplate.opsForValue().set("user:",redis.getUsername());
        return Result.ok("User saved to Redis");
    }

    @GetMapping("/saves")
    public Result saveTest1() {
        Redis redis = new Redis();
        redis.setUsername("wangba");
        // 使用 RedisTemplate 存储 Redis 对象
//        stringRedisTemplate.opsForValue().set("stringuser:",redis.getUsername());
        stringRedisTemplate.opsForValue().set("stringuser:",redis.getUsername());
        return Result.ok("stringUser saved to Redis");
    }

    @GetMapping("/gets")
    public Result gets() {
        String result = stringRedisTemplate.opsForValue().get("stringuser:");
        return Result.ok(result);
    }

    @GetMapping("/delete")
    public Result delete() {
        String key = "user:";
        Boolean delete = redisTemplate.delete(key);
        if(delete) {
            return Result.ok("User delete to Redis");
        } else {
            return Result.fail("User not delete to Redis");
        }
    }


    @GetMapping("/getcode")
    public Result getcode(@RequestBody LoginDTO loginDTO) {
        try {
            String getcode = redisService.getcode(loginDTO);
            return Result.ok(getcode);
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        try {
            redisService.login(loginDTO);
            return Result.ok("Login successfully");
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        }
    }

}
